package com.tangsm.spring.boot.api.exception;

import cn.hutool.core.util.ArrayUtil;
import com.tangsm.spring.boot.api.base.IResultCode;
import com.tangsm.spring.boot.api.enums.ResultCode;

import java.text.MessageFormat;

/**
 * 自定义API异常
 *
 * @author tangsm
 */
public class ApiException extends RuntimeException {

    private static final long serialVersionUID = 1921586608127303750L;

    private final IResultCode resultCode;

    private Object[] msgParams = null;

    /**
     * 有参构造，按响应状态码枚举构建业务异常
     *
     * @param resultCode 响应状态码枚举
     */
    public ApiException(IResultCode resultCode) {
        this.resultCode = resultCode;
    }

    /**
     * 有参构造，按响应状态码枚举构建业务异常
     *
     * @param resultCode 响应状态码枚举
     * @param msgParams  占位符可变长参数
     */
    public ApiException(IResultCode resultCode, Object... msgParams) {
        this.resultCode = resultCode;
        this.msgParams = msgParams;
    }

    /**
     * 返回此可抛出的详细消息字符串
     *
     * @return 消息字符串 (可能为null )
     */
    @Override
    public String getMessage() {
        if (ArrayUtil.isEmpty(this.msgParams)) {
            return this.resultCode.getMsg();
        }

        return MessageFormat.format(this.resultCode.getMsg(), this.msgParams);
    }

    public IResultCode getResultCode() {
        return resultCode;
    }

    public Object[] getMsgParams() {
        return msgParams;
    }
}
